package com.ssm.reader.controller.management;

import com.ssm.reader.entity.User;
import com.ssm.reader.service.UserService;
import com.ssm.reader.service.exception.BussinessException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

/*
 *
 *
 *@data 2022-05-05
 */
@Controller
@RequestMapping("/management/user")
public class MUserController {
    @Resource
    private UserService userService;


    //登录页
    @GetMapping()
    public ModelAndView showLogin(){
        ModelAndView modelAndView = new ModelAndView("/management/login");
        return modelAndView;
    }

    @PostMapping("/check_login")
    @ResponseBody
    public Map checkLogin(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        Map result = new HashMap();
        try {
            User user = userService.checkLogin(username,password);
            HttpSession session = request.getSession();
            //向session存入登录用户信息，属性名：login_user
            session.setAttribute("login_user",user);
            result.put("code","0");
            result.put("message","success");
            result.put("redirect_url","/management/index.html");
        } catch (BussinessException ex) {
            result.put("code",ex.getCode());
            result.put("message",ex.getMessage());
        }catch (Exception ex){
            result.put("code",ex.getClass().getSimpleName());
            result.put("message",ex.getMessage());
        }
        return result;
    }
}
